package com.gitee.validation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author gcq
 * @Create 2022-07-18
 */
public class PhoneValidator implements ConstraintValidator<Phone, String> {


    @Override
    public void initialize(Phone constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }
    /**
     * 自定义效验逻辑方法
     *
     * @param value
     * @param context
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 手机号验证规则: 158开头后面随便
        String check = "158\\d{8}";
        Pattern regex = Pattern.compile(check);

        String phone = Optional.ofNullable(value).orElse("");
        Matcher matcher = regex.matcher(phone);
        return matcher.matches();
    }
}